
/**
 * 学习javascript精粹这本书。
 * 
 *  
 */

//
Function.prototype.method = function(name, func) {
	//有条件加入方法
	if(! this.prototype[name] )
	{
		this.prototype[name] = func;
	}

	return this;
}

Number.method('integer',function(){
	return Math[this< 0?'ceil':'floor'](this);
});

String.method('trim', function(){
	return this.replace(/^\s+|\s+$/g, '')
});

//递归遍历DOM
var walk_the_DOM = function walk(node, func){
	
	func(node);
	node = node.firstChild;
	while(node){
		walk(node)
		node = node.nextSibling;
	}
};

//add a mothod 
var getElementsByAttribute = function(attr, value){
	var retsult = [];
	
	walk_the_DOM(document.body, function(node){
		var actual = node.nodeType == 1 && node.getAttribute(attr);
		if(typeof actual ==='string' &&
				(actual === value || typeof value !== 'string')){
			result.push(node);
		}
	});
}

// 对递归调用用的meno写法，即动态规划算法中的memo写法
var memoizer = function(memo, fundamental){
	var shell = function(n){
		var result = memo[n];
		if( typeof result !== 'number'){
			result = fundamental(shell, n);
			memo[n] = result;
		}
		return result;
	}
	
	return shell;
} 

var fibo = memoizer([0, 1], function(shell, n){
	return shell(n - 1) + shell ( n -2 );
});

Date.method('diffNDay', function(n){
	var newDate = new Date();
	newDate.setDate( this.getDate() + n);
	return newDate;
});

Date.method('diffNMonth', function(n){
	var newDate = new Date();
	newDate.setMonth( this.getMonth() + n);
	return newDate;
});
